<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2019-10-03
 * Time: 00:53
 */

namespace app\api\controller;
use app\common\controller\ApiController;
use think\Db;
class Community extends ApiController
{
    private $wy_bd_info;
    private $wy_imgs;

    function __construct(){
        parent::__construct();
        $this->wy_bd_info = Db::name('wy_bd_info');
        $this->wy_imgs = Db::name('wy_imgs');
    }

    // 小区列表
    public function getList() {
        $param = $this->request->get();
        $where[] = ['id','>',0];
        $where[] = ['is_deleted','=',0];
        if($this->userinfo['cm_message_id']) $where[] = ['id','in',$this->userinfo['cm_message_id']];
        if(@$param['name']) $where[] = ['name','like','%'.$param['name'].'%'];
        $where[] = ['pms_ar_id','=',$this->userinfo['pms_ar_id']];
        $list = $this->wy_bd_info->alias('w')->where($where)->page(empty($param['pageNo']) ? 1 : $param['pageNo'],10)->select();
        $houseModel=model('wy_houses');
        foreach($list as $k=>$v){
            $list[$k]['area']=getAreaStr($v['area']);
            $list[$k]['nums']=$houseModel->where('bd_info_id',$v['id'])->sum('num');
            $allHouse=$houseModel->where('bd_info_id',$v['id'])->count();
            $jfHouse=$houseModel->where('bd_info_id',$v['id'])->where('over_house',1)->count();
            $gtHouse=$houseModel->where('bd_info_id',$v['id'])->where('is_gt',1)->count();
            $list[$k]['nums']=$houseModel->where('bd_info_id',$v['id'])->sum('num');
            $list[$k]['jfHouse']=$jfHouse;
            $list[$k]['allHouse']=$allHouse;
            $list[$k]['wjfHouse']=$allHouse-$jfHouse;
            $list[$k]['gtHouse']=$gtHouse;
        }
        $count = $this->wy_bd_info->where($where)->count();
        return __success('ok',['data'=>$list,'pageSize'=>$param['pageSize'],'pageNo'=>(int)$param['pageNo'],'totalPage'=>ceil($count / 10),'totalCount'=>(int)$count]);
    }
    public function get_bd_config_list(){
        $ar_id = $this->request->get('ar_id','0');
        // $cm_mg_id = $this->request->get('cm_mg_id','');
        $cm_mg_id = $this->userinfo['cm_message_id']?$this->userinfo['cm_message_id']:'';
        $list=model('wy_bd_info')->getIdList($ar_id,$cm_mg_id);
        return __success('ok',$list);
    }
    public function get_lab_list(){
        $ar_id = $this->request->get('ar_id','0');
        $list = Db::name('wy_labels')->where('pms_ar_id',$ar_id)->where('is_deleted',0)->field('id,name')->select();
        return __success('ok',$list);
    }
    public function get_user_list(){
        $list = ['0'=>'所有','1'=>'业主本人','2'=>'亲属','3'=>'租客','4'=>'朋友','5'=>'同事','6'=>'保姆','7'=>'司机','8'=>'装修人员','9'=>'其它'];
        return __success('ok',$list);
    }
    public function get_bd_user(){
        $ar_id = $this->request->get('ar_id','0');
        $list = Db::name('pms_employee')->where('pms_ar_id',$ar_id)->field('id,name')->select();
        $lit = [['id'=>0,'name'=>'所有操作员']];
        $list = array_merge($lit,$list);
        return __success('ok',$list);
    }
    public function get_cate(){
        $list = Db::name('wy_deposit_list')->where('type','=',2)->group('category')->field('category as name')->select();
        $lit = [['id'=>0,'name'=>'所有'],['id'=>-1,'name'=>'excel导入']];
        $list = array_merge($lit,$list);
        return __success('ok',$list);
    }
    // 添加or编辑小区
    public function operation() {
        $param = $this->request->param();
        unset($param['token']);
        if($param['id'] == 0){
            if(empty($param['name'])) return __error('小区名称不可为空');
            if(empty($param['area'])) return __error('所在地区不可为空');
            if(empty($param['address'])) return __error('详细地址不可为空');
            if(is_array($param['area'])){
                $param['area'] = implode(',',$param['area']);
            }
            $ishas=model('wy_bd_info')->isHasName($param['name'],$param['area']);
            if($ishas) return __error('小区名称已经存在');
            $param['pms_ar_id'] = $this->userinfo['pms_ar_id'];
            $id = $this->wy_bd_info->strict(false)->insertGetId($param,true,true);
            if($this->userinfo['cm_message_id']){
               
                $cm_mg_id=explode(',',$this->userinfo['cm_message_id']);
                $cm_mg_id[]=$id;
                $this->userinfo['cm_message_id']=implode(',',$cm_mg_id);
                
                updateUserInfoByToken($this->token,$this->userinfo);
                Db::name('pms_employee')->where('id',$this->userinfo['id'])->update(['cm_message_id'=>$this->userinfo['cm_message_id']]);
            }
            return __success('添加成功',$id);
        }else{
            $upRes = $this->wy_bd_info->update($param);
            return $upRes !== false ? __success('保存成功',$param['id']) : __error('保存失败');
        }
    }

    // 保存小区其他信息
    public function saveBdExtendInfo() {
        $param = $this->request->param();
        $upRes = $this->wy_bd_info->update($param);
        return $upRes !== false ? __success('保存成功',$param['id']) : __error('保存失败');
    }

    // 获取小区信息
    public function getBdInfo() {
        $id = $this->request->param('id');
        if(empty($id)) return __error('参数错误');
        $info = $this->wy_bd_info->where('id',$id)->find();
        $imgsModel=model('wy_imgs');
        if(!empty($info['logo_file'])){
            $info['logo_file'] = $imgsModel->where('id','in',$info['logo_file'])->field('id uid,file_name name,url')->select()->toArray();
        }else $info['logo_file'] = [];
        if(!empty($info['bg_img'])){
            $info['bg_img'] = $imgsModel->where('id','in',$info['bg_img'])->field('id uid,file_name name,url')->select()->toArray();
        }else $info['bg_img'] = [];
        return !empty($info) ? __success('ok',$info) : __error('未知小区');
    }

    // 上传图片
    public function uploadPic() {
        $file = $this->request->file('file');
        $info = $file->validate(['size'=>2 * 1024 * 1024,'ext'=>'jpg,jpeg,png'])->move('./static/uploads');
        if($info){
            $fileName = $info->getInfo('name');
            $saveName = $info->getSaveName();
            $fileId = $this->wy_imgs->insertGetId(['url'=>$saveName,'createtime'=>date('Y-m-d H:i:s'),'file_name'=>$fileName]);
            return !empty($fileId) ? __success('上传成功',['id'=>$fileId,'url'=>$saveName,'file_name'=>$fileName]) : __error('上传失败');
        }else return __error($file->getError());
    }
    public function  upload_file(){
        $file = $this->request->file('file');
        $info = $file->validate(['ext'=>'xls,xlsx'])->move('./static/uploads');
        if($info){
            $pathName=$info->getPathName();
            return !empty($pathName) ? __success('上传成功',['pathName'=>$pathName]) : __error('上传失败');
        }else return __error($file->getError());
    }
    //获取楼宇列表
    public function get_bd_info_list(){
        $ar_id = $this->request->get('ar_id','0');
        // $cm_mg_id = $this->request->get('cm_mg_id','');
        $cm_mg_id = $this->userinfo['cm_message_id']?$this->userinfo['cm_message_id']:'';
        $name = $this->request->get('name');
        $page = $this->request->get('pageNo','1');
        $bd_info_id=$this->request->get('bd_info_id',0);
        if($bd_info_id){
            $where[]=[['bd_info_id','=',$bd_info_id]];
        }else{
            $where = [];
        }
        
        if($name) $where[] = ['name','like','%'.$name.'%'];
        $models=model('wy_building');
        $getdata=$models->getList($ar_id,$cm_mg_id,$page,$where);
        return __success('ok',$getdata);
    }
    //新增修改楼宇
    public function add_building_info(){
        $param = $this->request->post();
        unset($param['token']);
        if(empty($param['bd_info_id'])) return __error('小区不能为空');
        if(empty($param['name'])) return __error('楼宇名称不能为空');
        if($param['id'] == 0){
            if(empty($param['unit_num'])) return __error('单元数不能为空');
            if(empty($param['layers'])) return __error('楼层不能为空');
            $layers=$param['layers'];
            unset($layers['layers']);
        }
        
        $models=model('wy_building');
        // 查询楼宇信息->防止楼宇重复
        $buildingMap[] = ['name','=',$param['name']];
        $buildingMap[] = ['bd_info_id','=',$param['bd_info_id']];
        $buildingMap[] = ['is_deleted','=',0];
        if($param['id'] !== 0) $buildingMap[] = ['id','<>',$param['id']];
        $buildingInfo = $models->where($buildingMap)->find();
        if(!empty($buildingInfo)) return __error('楼宇名称重复');
        if($param['id'] == 0){
            $id = $models->strict(false)->insertGetId($param,true,true);
            $unitModels=model('wy_unit');
            $autoUnit=$unitModels->autoAddInfo($param['bd_info_id'],$id,(int)$param['unit_num'],$layers);
            if(!$autoUnit){
                return __error('新增成功！生成单元失败');
            }
            return __success('添加成功',$id);
        }else{
            $upRes = $models->update($param);
            return $upRes !== false ? __success('保存成功',$param['id']) : __error('保存失败');
        }
    }
    //获取楼宇信息
    public function get_building_info()
    {
        $id = $this->request->get('id');
        $ar_id = $this->userinfo['pms_ar_id'];
        $cm_mg_id =  $this->userinfo['cm_message_id'];
        $models=model('wy_building');
        $info=$models->getInfo($ar_id,$cm_mg_id,$id);
        return __success('ok',$info);
    }
    //删除楼宇列表
    public function del_building_info_list(){
        $ids = $this->request->post('ids');
        $ar_id = $this->userinfo['pms_ar_id'];
        $cm_mg_id =  $this->userinfo['cm_message_id'];
        $models=model('wy_building');
        $info=$models->delInfo($ar_id,$cm_mg_id,$ids);
        if($info){
            return __success('删除成功');
        }else {
            return __error('删除失败');
        }
       
    }
    //获取单元列表
    public function get_unit_list(){
        $ar_id = $this->request->get('ar_id','0');
        $bid = $this->request->get('bid','0');
        // $cm_mg_id = $this->request->get('cm_mg_id','');
        $cm_mg_id = $this->userinfo['cm_message_id']?$this->userinfo['cm_message_id']:'';
        $page = $this->request->get('pageNo','1');
        $name = $this->request->get('name');
        $where = [];
        if($name) $where[] = ['name','like','%'.$name.'%'];
        $models=model('wy_unit');
        $getdata=$models->getList($ar_id,$cm_mg_id,$bid,$page,$where);
        return __success('ok',$getdata);
    }
    //删除单元
    public function del_unit_list(){
        $ids = $this->request->post('ids');
        $ar_id = $this->userinfo['pms_ar_id'];
        $cm_mg_id =  $this->userinfo['cm_message_id'];
        if(empty($ids)) return __error('参数错误');

        $models=model('wy_unit');
        $hasHouse=db('wy_houses')->where('unit_id','in',$ids)->where('is_deleted','=',0)->find();
        if($hasHouse){
            return __error('单元下有房间禁止删除');
        }
        $info=$models->delInfo($ar_id,$cm_mg_id,$ids);
        if($info){
            return __success('删除成功');
        }else {
            return __error('删除失败');
        }
    }
    //编辑单元
    public function edit_unit_list(){
        $id = $this->request->post('id');
        $name = $this->request->post('name');
        // $middle_layers = $this->request->post('middle_layers');
        $layers = $this->request->post('layers');
        $building_id = $this->request->post('bid');
        $modelsBD=model('wy_building');
        $bd_info_id=$modelsBD->where('id',$building_id)->value('bd_info_id');
        $models=model('wy_unit');
        if($models->ishasname($bd_info_id,$building_id,$name,$id)){
            return __error('名称已存在！');
        }
        if($id){
            $info=$models->editInfo($bd_info_id,$building_id,$id,$name,$layers);
            if($info){
                return __success('修改成功');
            }else {
                return __error('修改失败');
            }
        }else {
            $info=$models->addInfo($bd_info_id,$building_id,$name,$layers);
            if($info){
                return __success('添加成功');
            }else {
                return __error('添加失败');
            }
        }
        
    }
    public function import_building_info(){
        $bd_info_id = $this->request->post('bd_info_id');
        $fileList = $this->request->post('fileList');
        $site = $this->request->post('site');
        ignore_user_abort(true); 
        set_time_limit(0); 
        echo json_encode(inExcel($fileList['file']['response']['data']['pathName'],$bd_info_id,'wy_houses'));
        die;
    }
    public function import_parking_info(){
        $bd_info_id = $this->request->post('bd_info_id');
        $fileList = $this->request->post('fileList');
        $site = $this->request->post('site');
        ignore_user_abort(true); 
        set_time_limit(0); 
        echo json_encode(inExcel($fileList['file']['response']['data']['pathName'],$bd_info_id,'wy_car_area'));
        die;
    }
    public function import_vehicle_info(){
        $bd_info_id = $this->request->post('bd_info_id');
        $fileList = $this->request->post('fileList');
        $site = $this->request->post('site');
        ignore_user_abort(true); 
        set_time_limit(0); 
        echo json_encode(inExcel($fileList['file']['response']['data']['pathName'],$bd_info_id,'wy_car'));
        die;
    }
    public function import_household_info(){
        $bd_info_id = $this->request->post('bd_info_id');
        $fileList = $this->request->post('fileList');
        $page=$this->request->post('page');
        $site = $this->request->post('site');
        ignore_user_abort(true); 
        set_time_limit(0); 
        echo json_encode(inExcel($fileList['file']['response']['data']['pathName'],$bd_info_id,'wy_house_user',1,'lsx',0,$page));
        die;
    }
    /***首页控制台功能 */
    public function getHomeBase(){
        $ar_id = $this->userinfo['pms_ar_id'];
        $cm_mg_id =  $this->userinfo['cm_message_id'];
        if($cm_mg_id){
            $where[]=['bd_info_id','in',$cm_mg_id];
        }else {
            $getMgIds=model('wy_bd_info')->dbIds($ar_id);
            if($getMgIds){
                $where[]=['bd_info_id','in',$getMgIds];
            }else {
                $where[]=['bd_info_id','=',0];
            }
            
        }
        $data['mgCount']=model('wy_bd_info')->where('pms_ar_id',$ar_id)->where('is_deleted',0)->count();
        $data['buildingCount']=model('wy_building')->where($where)->where('is_deleted',0)->count();
        $data['houseCount']=model('wy_houses')->where($where)->where('is_deleted',0)->count();
        $houseIds=model('wy_houses')->where($where)->where('is_deleted',0)->column('id');
        $data['houseUserCount']=Db::name('wy_houses_user_middle')->where('houses_id','in',$houseIds)->count();
        $data['carCount']=model('wy_car')->where($where)->where('is_deleted',0)->count();
        $data['carAreaCount']=model('wy_car_area')->where($where)->where('is_deleted',0)->count();
        return __success('ok',$data);
    }
    public function getNewGg(){
        $data=DB::name('yt_article')->where('category_id',7)->limit(10)->select();
        return __success('ok',$data);
    }
}